package com.chen.webuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.webuser.entity.Dynamic;
import com.chen.webuser.entity.WebUser;
import com.chen.webuser.mapper.DynamicMapper;
import com.chen.webuser.service.DynamicService;
import com.chen.webuser.service.WebUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chen
 * @since 2025-10-22
 */
@Service
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic> implements DynamicService {

    @Autowired
    private WebUserService webUserService;
    @Autowired
    private DynamicMapper dynamicMapper;

    /**
     * 获取动态列表
     *
     * @return
     */
    @Override
    public List<Dynamic> listDynamic() {

        LambdaQueryWrapper<Dynamic> queryWrapper = new LambdaQueryWrapper<>();
        //按照发布日期排序
        queryWrapper.orderByDesc(Dynamic::getPostTime);

        List<Dynamic> dynamicList = dynamicMapper.selectList(queryWrapper);


        // 查询出userId的集合
        List<Integer> userIdList = dynamicList.stream().map((dynamic) -> {
            return dynamic.getUid();
        }).collect(Collectors.toList());

        // 根据userId集合查询user信息,这个webUser已经封装了webUserInfo
        List<WebUser> webUserList = webUserService.selectByIds(userIdList);


        for (Dynamic dynamic : dynamicList) {
            for (WebUser webUser : webUserList) {
                if (dynamic.getUid().equals(webUser.getUid())) {
                    dynamic.setWebUser(webUser);
                }
            }
        }

        //TODO  查询出带有头像的用户信息


        return dynamicList;
    }

    /**
     * 保存动态
     * @param dynamic
     */
    @Override
    public void saveDynamic(Dynamic dynamic) {
        dynamic.setPostTime(LocalDateTime.now());
        save(dynamic);
    }
}
